package gops

import (
	"crypto/tls"
	"fmt"
	"log"
	"time"

	"gopkg.in/mail.v2"
)

type mailer struct {
	dialer *mail.Dialer
}

type mailNewConfig struct {
	Host     string `json:"host"`
	User     string `json:"user"`
	Password string `json:"password"`
	Port     int    `json:"port"`
	SmtpSSL  bool   `json:"smtp_ssl"`
}

func MailNew(config *mailNewConfig) *mailer {
	dialer := mail.NewDialer(config.Host, config.Port, config.User, config.Password)
	dialer.TLSConfig = &tls.Config{InsecureSkipVerify: config.SmtpSSL}
	return &mailer{dialer: dialer}
}

func (m *mailer) log(content string) {
	nowTime := time.Now().Format("15:04:05")
	fmt.Printf("INFO [%s]: %s\n", nowTime, content)
}

func (m *mailer) MailSendMsg(title, msg, receiver string) (err error) {
	m.log(fmt.Sprintf("开始给 %s 发送邮件...", receiver))

	message := mail.NewMessage()
	message.SetHeader("From", m.dialer.Username)
	message.SetHeader("To", receiver)
	message.SetHeader("Subject", title)
	message.SetBody("text/plain", msg)

	err = m.dialer.DialAndSend(message)
	if err != nil {
		log.Printf("Error: 发送邮件失败! %v\n", err)
		return
	}
	m.log("发送成功")
	return nil
}

func (m *mailer) MailSendAttachFile(title, msg, filePath, receiver string) (err error) {
	m.log(fmt.Sprintf("开始给 %s 发送邮件...", receiver))

	message := mail.NewMessage()
	message.SetHeader("From", m.dialer.Username)
	message.SetHeader("To", receiver)
	message.SetHeader("Subject", title)
	message.SetBody("text/plain", msg)
	message.Attach(filePath)

	err = m.dialer.DialAndSend(message)
	if err != nil {
		log.Printf("Error: 发送邮件失败! %v\n", err)
		return
	}
	m.log("发送成功")
	return nil
}

//func main() {
//	mail := gops.NewMail(&gops.mailNewConfig{
//		Host: "192.xx.4.xx",
//		User: "test@xxxx.show",
//		Password: "xxxxxxx",
//		Port: 26016,
//		SmtpSSL: true,
//	})
//	mail.SendMsgMail("测试", "测试", "xxx@126.com")
//}
